
from Queue import Queue, Empty
from kivy.logger import Logger
from threading import Thread


class Message(object):
	def __init__(self, method, *args, **kwargs):
		self.method = method
		self.args = args
		self.kwargs=kwargs

	def __call__(self):
		return self.method(*self.args, **self.kwargs)

class CommandRunner(Thread):
	def __init__(self, send_queue, *args, **kwargs):
		Thread.__init__(self, name=self.__class__.__name__)
		self.queue = Queue()
		self._stop = False
		self.send_queue = send_queue

	def stop(self):
		self._stop = True

	def thread_started(self):
		pass

	def notify(self, message):
		self.send_queue.put(message)

	def run(self):
		try:
			self.thread_started()
			Logger.info("Start of %s loop", self.__class__.__name__)
			while not self._stop:
				try:
					event = self.queue.get(True, 0.5)
				except Empty:
					pass
				else:
					method = getattr(self, event.method, None)
					if method:
						try:
							Logger.info("Running %s(%s, %s)", event.method, event.args, event.kwargs)
							result = method(*event.args, **event.kwargs)
							if result:
								self.send_queue.put(result)
						except:
							Logger.exception("Problem when running command %s", method)
					else:
						Logger.error("Method %s not found on %s", event.method, self.__class__.__name__)
		finally:
			Logger.info("End of %s loop", self.__class__.__name__)

